package com.tyler.voice;

import jakarta.websocket.Endpoint;
import jakarta.websocket.EndpointConfig;
import jakarta.websocket.Session;
import org.glassfish.tyrus.client.ClientManager;

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

public class WebSocketClient {
    private String cServerUrl;
    private Session cSession;
    private CountDownLatch connectLatch = new CountDownLatch(1);

    public WebSocketClient(String cServerUrl) {
        this.cServerUrl = cServerUrl;
    }

    // 连接
    public void connect() {
        new Thread(() -> {
            ClientManager client = ClientManager.createClient();
            try {
                client.connectToServer(new Endpoint() {
                    @Override
                    public void onOpen(Session session, EndpointConfig config){
                        cSession = session;
                        connectLatch.countDown();
                        System.out.println("已连接到 C项目 WebSocket 服务");
                    }
                }, new URI(cServerUrl));
                connectLatch.await(); // 等待连接建立
            } catch (Exception e) {
                System.out.println("连接 C项目失败："+e.getMessage());
            }
        }).start();
    }

    // 发送文本消息（新增方法）
    public void sendText(String text) {
        if (cSession != null && cSession.isOpen()) {
            try {
                cSession.getBasicRemote().sendText(text); // 直接发送文本
            } catch (IOException e) {
                System.out.println("向 C项目发送文本失败："+e.getMessage());
            }
        }
    }

    // 保留原发送二进制数据的方法（用于音频数据）
    public void send(byte[] data) {
        if (cSession != null && cSession.isOpen()) {
            try {
                cSession.getBasicRemote().sendBinary(ByteBuffer.wrap(data));
            } catch (IOException e) {
                System.out.println("向 C项目发送数据失败："+e.getMessage());
            }
        }
    }

    // 断开与C项目的连接
    public void disconnect() {
        if (cSession != null) {
            try {
                cSession.close();
            } catch (IOException e) {
                System.out.println("断开 C项目连接失败："+e.getMessage());
            }
        }
    }

}
